package com.s2paganini.data 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;		

	/**
	 * @author siLvio paganini | s2paganini.com
	 * @category: Reader Abstract Class
	 * 
	 * Should be extended by the custom Reader
	 * Override the function "parseFeed" with custom actions
	 */
	public class Reader extends EventDispatcher 	{
		private var loader : URLLoader;
		private var request : URLRequest;
		public function Reader() : void
		{
		}
		/**
		 * @param: whichURL The url to load
		 */
		protected function loadFeed(whichURL : String) : void
		{
			loader = new URLLoader();
			
			request = new URLRequest(whichURL);
			request.method = URLRequestMethod.GET;
									
			loader.addEventListener(Event.COMPLETE, dataLoaded, false, 0, true);
			loader.addEventListener(IOErrorEvent.IO_ERROR, IOeventError, false, 0, true);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError, false, 0, true);
			loader.load(request);
		}
		
		private function securityError(event : SecurityErrorEvent) : void
		{
			trace(event.text);
		}
		private function IOeventError(event : IOErrorEvent) : void
		{
			throw new Error(event.text);
		}
		
		/**
		 * Loads the XML and calls the overriden function <code>parseFeed</code>
		 */		private function dataLoaded(event : Event) : void
		{
			var feed : String = URLLoader(event.target).data;
			parseFeed(feed);		
		}
		
		/**
		 * Override this function with the customized XML parser
		 * @param feed XML string loaded
		 */		protected function parseFeed(feed : String) : void
		{
		}
	}
}
